package com.lxy.controller;

import com.lxy.config.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidBucketNameException;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.XmlParserException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lixueyang
 * @since 2022/4/22 9:19
 */
@RestController
@RequestMapping("/")
public class UploadController {

    @Resource
    private MinioProperties minioProperties;

    @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile file) throws InvalidPortException, InvalidEndpointException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {


        MinioClient minioClient = new MinioClient(minioProperties.getEndpoint(), minioProperties.getAccessKey(), minioProperties.getSecretKey());

        String bucketName = "cloud-disk";
        boolean isExist = minioClient.bucketExists(bucketName);

        if (!isExist) {
            return "";
        }
        String filename = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        //设置存储对象名称
        String objectName = sdf.format(new Date()) + "/" + filename;
        //把存储对象上传到存储桶中

        minioClient.putObject(bucketName, objectName, file.getInputStream(), new PutObjectOptions(file.getInputStream().available(), -1));
        System.out.println("文件上传成功");

        return minioClient.getObjectUrl(bucketName, objectName);
    }
}
